package com.yyoa.controller;

import java.util.Map;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.yyoa.Consts;
import com.yyoa.entity.User;
import com.yyoa.model.Page;
import com.yyoa.service.UserService;
import com.yyoa.util.CookieUtil;

@Controller("userController")
@RequestMapping("/user")
public class UserController extends BaseController {

	// logger日志对象
	protected Logger log = Logger.getLogger(this.getClass());

	private UserService userService;

	@ResponseBody
	@RequestMapping(value = "/login")
	public Map<String, String> login(HttpServletRequest httpRequest, HttpServletResponse httpResponse) {
		log.info("Begin goTo login.");

		String userName = httpRequest.getParameter("userName");
		String password = httpRequest.getParameter("password");
		User dbUser = userService.login(userName, password);
		if (dbUser == null) {
			log.info("login failed.");
			httpRequest.getSession().setAttribute("errorInfo", "用户名或密码错误，请重新登录！");
			return handleGotoPage("/login/index.html");
		}

		// 定义账户密码的生命周期，这里是一个月。单位为秒
		int loginMaxAge = Consts.LOGINMAXAGE * 24 * 60 * 60;
		String rememberPwd = httpRequest.getParameter("rememberPwd") == null ? ""
				: httpRequest.getParameter("rememberPwd").toString();
		if ("true".equals(rememberPwd)) {
			// 将登录信息加入到cookie中
			CookieUtil.addCookie(httpResponse, "loginName", userName, loginMaxAge);
			CookieUtil.addCookie(httpResponse, "loginPwd", password, loginMaxAge);
			CookieUtil.addCookie(httpResponse, "role", String.valueOf(dbUser.getRole()), loginMaxAge);
			CookieUtil.addCookie(httpResponse, "loginRememberPwd", rememberPwd, loginMaxAge);
		} else {
			CookieUtil.addCookie(httpResponse, "loginName", null, 0);
			CookieUtil.addCookie(httpResponse, "loginPwd", null, 0);
			CookieUtil.addCookie(httpResponse, "role", null, 0);
			CookieUtil.addCookie(httpResponse, "loginRememberPwd", null, 0);
		}
		httpRequest.getSession().setAttribute("user", dbUser);
		return handleGotoPage("/main/index.html");
	}

	@ResponseBody
	@RequestMapping(value = "/getUser")
	public User getUser(HttpServletRequest httpRequest, HttpServletResponse httpResponse) {
		String userName = httpRequest.getParameter("userName");
		String password = httpRequest.getParameter("password");
		log.info("Get user info by userName [" + userName + "] and password [" + password + "].");

		return userService.login(userName, password);
	}

	@ResponseBody
	@RequestMapping(value = "/verifyUser")
	public boolean verifyUser(HttpServletRequest httpRequest, HttpServletResponse httpResponse) {
		String userName = httpRequest.getParameter("userName");
		String mobilePhoneOrEmail = httpRequest.getParameter("mobilePhoneOrEmail");
		log.info("Get to verify user is exit:userName [" + userName + "], mobilePhoneOrEmail [" + mobilePhoneOrEmail
				+ "].");
		return userService.verifyUser(userName, mobilePhoneOrEmail);
	}

	@ResponseBody
	@RequestMapping(value = "/getByUserName")
	public User getByUserName(HttpServletRequest httpRequest, HttpServletResponse httpResponse) {
		String userName = httpRequest.getParameter("userName");
		log.info("Get to get user by userName [" + userName + "].");
		return userService.getByUserName(userName);
	}

	@ResponseBody
	@RequestMapping(value = "/getByEmail")
	public User getByEmail(HttpServletRequest httpRequest, HttpServletResponse httpResponse) {
		String email = httpRequest.getParameter("email");
		log.info("Get to get user by email [" + email + "].");
		return userService.getByEmail(email);
	}

	@ResponseBody
	@RequestMapping(value = "/getByMobilePhone")
	public User getByMobilePhone(HttpServletRequest httpRequest, HttpServletResponse httpResponse) {
		String mobilePhone = httpRequest.getParameter("mobilePhone");
		log.info("Get to get user by mobilePhone [" + mobilePhone + "].");
		return userService.getByMobilePhone(mobilePhone);
	}

	@ResponseBody
	@RequestMapping(value = "/resetPassword")
	public boolean resetPassword(HttpServletRequest httpRequest, HttpServletResponse httpResponse) {
		String userName = httpRequest.getParameter("userName");
		log.info("Get to reset user [" + userName + "] password.");
		String resetPassword = httpRequest.getParameter("resetPassword");
		userService.resetPassword(userName, resetPassword);
		return true;
	}

	@ResponseBody
	@RequestMapping(value = "/updateUserPw")
	public boolean updateUserPw(HttpServletRequest httpRequest, HttpServletResponse httpResponse) {
		String userName = httpRequest.getParameter("userName");
		String password = httpRequest.getParameter("password");
		String newPassword = httpRequest.getParameter("newPassword");

		log.info("Get to update user password userName [" + userName + "], password [" + password + "], newPassword ["
				+ newPassword + "] .");
		User dbUser = userService.login(userName, password);
		if (dbUser != null) {
			userService.resetPassword(userName, newPassword);
			return true;
		}
		return false;
	}

	@ResponseBody
	@RequestMapping(value = "/updateUser")
	public boolean updateUser(HttpServletRequest httpRequest, HttpServletResponse httpResponse) {
		User user = getUser(httpRequest);
		log.info("Get to update user [" + user + "] .");
		userService.updateUser(user);
		return true;
	}

	@ResponseBody
	@RequestMapping(value = "/list")
	@SuppressWarnings("unchecked")
	public Page<User> listUser(HttpServletRequest httpRequest, HttpServletResponse httpResponse) {
		log.info("Get to list user information:");
		Page<User> users = userService.listUser(initPage(httpRequest), initConstraint(httpRequest, User.class));
		for (User user : users.getResult()) {
			user.setPassword(null);
		}
		return users;
	}

	@ResponseBody
	@RequestMapping(value = "/modify")
	public void modify(HttpServletRequest httpRequest, HttpServletResponse httpResponse) {
		log.info("Get to modify user.");
		User user = getUser(httpRequest);
		String oper = httpRequest.getParameter("oper");
		if ("add".equals(oper)) {
			log.info("Get to add user [" + user + "] .");
			userService.addCommonUser(user);
		} else if ("del".equals(oper)) {
			String loginUserName = CookieUtil.getCookieByName(httpRequest, "loginName").getValue();
			Long deleteUserId = user.getId();
			log.info("Get to delete user id [" + deleteUserId + "] .");
			userService.deleteUser(loginUserName, deleteUserId);
		} else if ("edit".equals(oper)) {
			log.info("Get to update user [" + user + "] .");
			userService.updateUser(user);
		}
	}

	private User getUser(HttpServletRequest httpRequest) {
		User user = new User();
		String id = httpRequest.getParameter("id");
		if (id != null && !"_empty".equals(id)) {
			user.setId(Long.parseLong(id));
		}
		user.setUserName(httpRequest.getParameter("userName"));
		user.setName(httpRequest.getParameter("name"));
		user.setEmail(httpRequest.getParameter("email"));
		user.setSex(httpRequest.getParameter("sex"));
		user.setDescribe(httpRequest.getParameter("describe"));
		user.setPhone(httpRequest.getParameter("phone"));
		String mobielNumber = httpRequest.getParameter("mobilePhone");
		if (StringUtils.isNotEmpty(mobielNumber)) {
			user.setMobilePhone(Long.parseLong(mobielNumber));
		}
		return user;
	}

	@ResponseBody
	@RequestMapping(value = "/delete")
	public void delete(HttpServletRequest httpRequest, HttpServletResponse httpResponse) {
		System.out.println("Delete run.....");
	}

	@Autowired
	public void setUserService(UserService userService) {
		this.userService = userService;
	}
}
